<template>
  <el-dialog
      v-model="visible"
      title="发起签约申请"
      width="600px"
      :before-close="handleClose"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="form.realName" placeholder="请输入真实姓名" />
      </el-form-item>
      <el-form-item label="身份证号" prop="identityCard">
        <el-input v-model="form.identityCard" placeholder="请输入身份证号" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="租赁开始日期" prop="startDate">
        <el-date-picker
            v-model="form.startDate"
            type="date"
            placeholder="选择租赁开始日期"
            style="width: 100%"
            :disabled-date="disabledStartDate"
        />
      </el-form-item>
      <el-form-item label="租赁时长" prop="leaseTerm">
        <el-select v-model="form.leaseTerm" placeholder="请选择租赁时长" @change="calculateEndDate">
          <el-option
              v-for="month in leaseTerms"
              :key="month"
              :label="`${month}个月`"
              :value="month"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="租赁结束日期" prop="endDate">
        <el-date-picker
            v-model="form.endDate"
            type="date"
            placeholder="租赁结束日期（自动计算）"
            style="width: 100%"
            disabled
        />
      </el-form-item>
      <el-form-item label="月租金" prop="monthRent">
        <el-input-number
            v-model="form.monthRent"
            :min="0"
            :precision="2"
            placeholder="请输入月租金"
            style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="押金" prop="deposit">
        <el-input-number
            v-model="form.deposit"
            :min="0"
            :precision="2"
            placeholder="请输入押金"
            style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentType">
        <el-select v-model="form.paymentType" placeholder="请选择支付方式">
          <el-option label="月付" :value="1" />
          <el-option label="季付" :value="2" />
          <el-option label="年付" :value="3" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose" :disabled="submitting">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          {{ submitting ? '提交中...' : '提交' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, defineProps, defineEmits, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  houseId: {
    type: [Number, String],
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
const formRef = ref()
const submitting = ref(false)

// 临时信息值，用于API请求头
const TEMP_INFO_VALUE = '9fbf0bf9-350d-4fad-8799-acfbfa3dd579'

// 创建带有默认请求头的 axios 实例
const apiClient = axios.create({
  headers: {
    'info': TEMP_INFO_VALUE
  }
})

const form = reactive({
  realName: '',
  identityCard: '',
  phone: '',
  startDate: '',
  leaseTerm: 12,
  endDate: '',
  monthRent: 0,
  deposit: 0,
  paymentType: 1
})

const rules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5]{2,10}$/, message: '请输入2-10位中文姓名', trigger: 'blur' }
  ],
  identityCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  startDate: [
    { required: true, message: '请选择租赁开始日期', trigger: 'change' }
  ],
  leaseTerm: [
    { required: true, message: '请选择租赁时长', trigger: 'change' }
  ],
  monthRent: [
    { required: true, message: '请输入月租金', trigger: 'blur' },
    { type: 'number', min: 1, message: '月租金必须大于0', trigger: 'blur' }
  ],
  deposit: [
    { required: true, message: '请输入押金', trigger: 'blur' },
    { type: 'number', min: 0, message: '押金不能小于0', trigger: 'blur' }
  ],
  paymentType: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
}

const leaseTerms = [6, 12, 18, 24, 36]

// 监听modelValue变化
watch(() => props.modelValue, (val) => {
  visible.value = val
})

// 监听visible变化
watch(visible, (val) => {
  emit('update:modelValue', val)
  if (!val) {
    resetForm()
  }
})

// 禁用过去的日期
const disabledStartDate = (date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return date.getTime() < today.getTime()
}

// 计算结束日期
const calculateEndDate = () => {
  if (form.startDate && form.leaseTerm) {
    const startDate = new Date(form.startDate)
    const endDate = new Date(startDate)
    endDate.setMonth(endDate.getMonth() + form.leaseTerm)
    form.endDate = endDate
  }
}

// 监听开始日期变化，自动计算结束日期
watch(() => form.startDate, () => {
  calculateEndDate()
})

// 重置表单
const resetForm = () => {
  form.realName = ''
  form.identityCard = ''
  form.phone = ''
  form.startDate = ''
  form.leaseTerm = 12
  form.endDate = ''
  form.monthRent = 0
  form.deposit = 0
  form.paymentType = 1
}

// 关闭对话框
const handleClose = () => {
  if (submitting.value) {
    ElMessage.warning('正在提交中，请稍候...')
    return
  }
  visible.value = false
}

// 获取当前用户信息
const getCurrentUser = () => {
  const user = localStorage.getItem('user')
  if (!user) {
    throw new Error('请先登录')
  }
  return JSON.parse(user)
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) {
    ElMessage.error('表单引用不存在')
    return
  }

  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请填写完整信息')
      return
    }

    submitting.value = true

    try {
      // 获取当前用户信息
      const user = getCurrentUser()
      const tenantId = user.id || user.userId

      if (!tenantId) {
        throw new Error('用户信息不完整，请重新登录')
      }

      // 准备签约申请数据
      const contractData = {
        userId: tenantId,
        houseId: Number(props.houseId),
        landlordId: null, // 需要从房源信息中获取
        realName: form.realName,
        idCard: form.identityCard,
        phone: form.phone,
        leaseStartDate: form.startDate,
        leaseEndDate: form.endDate,
        monthlyRent: form.monthRent,
        deposit: form.deposit,
        paymentMethod: form.paymentType
      }

      // 首先获取房源信息以获取房东ID
      const houseResponse = await apiClient.get(`/housingHub/house/${props.houseId}`)

      if (houseResponse.data.code !== 200 && houseResponse.data.code !== '200') {
        throw new Error(houseResponse.data.message || '获取房源信息失败')
      }

      const houseData = houseResponse.data.data?.body
      if (!houseData) {
        throw new Error('房源信息不存在')
      }

      // 设置房东ID
      contractData.landlordId = houseData.landlord?.landlordId

      if (!contractData.landlordId) {
        throw new Error('房源房东信息不完整')
      }

      console.log('提交签约申请数据:', contractData)

      // 调用签约申请API
      const response = await apiClient.post('/housingHub/contract/tenant/applyContract', contractData)

      if (response.data.code === 200 || response.data.code === '200') {
        ElMessage.success('签约申请已提交，请等待房东处理')
        visible.value = false
        emit('success')
      } else {
        throw new Error(response.data.message || '签约申请提交失败')
      }

    } catch (error) {
      console.error('提交签约申请失败:', error)

      let errorMessage = '签约申请提交失败，请稍后重试'

      if (error.response) {
        const status = error.response.status
        if (status === 400) {
          errorMessage = '申请信息有误，请检查后重试'
        } else if (status === 409) {
          errorMessage = '该房源已有签约申请，请勿重复申请'
        } else if (status === 403) {
          errorMessage = '没有权限进行签约申请'
        } else if (status === 404) {
          errorMessage = '房源不存在或已下架'
        }
      } else if (error.message) {
        errorMessage = error.message
      }

      ElMessage.error(errorMessage)
    } finally {
      submitting.value = false
    }
  })
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
